package com.luban;

import com.luban.service.TestProxyInterface;
import com.luban.service.TestProxyService;
import org.springframework.aop.AfterAdvice;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.BeforeAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxyTest {

	public static void main(String[] args) {

		//1. JDK动态代理
//		TestProxyService testProxyService = new TestProxyService(); //目标对象
//		TestProxyInterface proxyInstance = (TestProxyInterface)Proxy.newProxyInstance(TestProxyService.class.getClassLoader(), TestProxyService.class.getInterfaces(), new InvocationHandler() {
//			@Override
//			//参数Object proxy就是proxyInstance，
//			//参数Method method就是test()，
//			//参数Object[] args 就是test()方法的参数
//			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//				System.out.println("代理逻辑");
//				Object obj = method.invoke(testProxyService, args); //在代理逻辑中可以执行目标对象的方法
//				return obj;
//			}
//		}); //代理对象
//		proxyInstance.test();

		//2. 测试aop
		ProxyFactory factory = new ProxyFactory();
		factory.setTarget(new TestProxyService()); //目标对象
		factory.addAdvice(new AfterReturningAdvice() {
			@Override
			public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
//				System.out.println("代理逻辑afterReturning");
				System.out.println("执行["+method.getName()+"]方法后。。。");
			}
		});
		factory.addAdvice(new MethodBeforeAdvice() {
			@Override
			public void before(Method method, Object[] args, Object target) throws Throwable {
				System.out.println("执行["+method.getName()+"]方法前。。。");
			}
		});

		TestProxyInterface testProxyInterface = (TestProxyInterface)factory.getProxy();
		testProxyInterface.test();
	}

}
